package com.sunwayhorizo.health.platform.security.service.identity;

import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.ejb.Stateless;

import org.jboss.seam.Component;
import org.jboss.seam.annotations.Name;

import com.sunwayhorizo.health.business.dto.ResultsDTO;
import com.sunwayhorizo.health.common.ListUtil;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.platform.base.BaseManager;
import com.sunwayhorizo.health.platform.common.SecurityQueryConditions;
import com.sunwayhorizo.health.platform.security.dao.SecurityAccountDao;
import com.sunwayhorizo.health.platform.security.dao.SecurityAccountRoleDao;
import com.sunwayhorizo.health.platform.security.dao.SecurityAccountRolePermissionDao;
import com.sunwayhorizo.health.platform.security.dao.SecurityPermissionAccountDao;
import com.sunwayhorizo.health.platform.security.persistent.SecurityAccount;
import com.sunwayhorizo.health.platform.util.PropertiesUtil;

@Name("SecurityAccountManager")
@Stateless
public class SecurityAccountManager extends BaseManager implements SecurityAccountManagerLocal{

	@Override
	public ResultsDTO newSecurityAccount(SecurityAccount account) {
		SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
		account = accountDao.newSecurityAccount(account);
		return getResultsDTO("添加账号成功", true, account.getAccountId());
	}

	@Override
	public ResultsDTO delSecurityAccount(List<String> list) {
	    for(int i=0;ListUtil.isNotEmpty(list)&&i<list.size();i++){
	        SecurityAccount sa = super.find(SecurityAccount.class, list.get(i));
	        sa.setDeleted("1");
	        super.update(sa);
	    }
	    return getResultsDTO("删除账号成功", true, null);
		/*SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
		accountDao.deleteSecurityAccount(list);
		return getResultsDTO("删除账号成功", true, null);*/
	}

	@Override
	public ResultsDTO updateSecurityAccount(SecurityAccount account) {
		SecurityAccountRoleDao accountRoleDao = (SecurityAccountRoleDao)Component.getInstance("SecurityAccountRoleDao");
		accountRoleDao.deleteSecurityRoleByAccountId(account.getAccountId());
		
		SecurityPermissionAccountDao permissionAccountDao = (SecurityPermissionAccountDao)Component.getInstance("SecurityPermissionAccountDao");
		permissionAccountDao.deleteSecurityPermissionAccountByAccountId(account.getAccountId());
		
		SecurityAccountRolePermissionDao accountRolePermissionDao = (SecurityAccountRolePermissionDao)Component.getInstance("SecurityAccountRolePermissionDao");
		accountRolePermissionDao.deleteSecurityAccountRolePermissionByAccountId(account.getAccountId()); 
		
		SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
		accountDao.updateSecurityAccount(account);
		return super.getResultsDTO("修改账号成功",true, null);
	}
	
	@Override
	public ResultsDTO updateSecurityAccountPassword(SecurityAccount account) {
		SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
		accountDao.updateSecurityAccountPassword(account);
		return super.getResultsDTO("修改密码成功",true, null);
	}

	@Override
	public ResultsDTO findSecurityAccountList() {
		SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
		return super.getResultsDTO("查询账号列表成功",true, accountDao.findSecurityAccountList());
	}

	@Override
	public ResultsDTO findSecurityAccountDetailById(String accountId) {
		SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
		return super.getResultsDTO("通过角色查询账号列表成功",true, accountDao.findSecurityAccountDetailById(accountId));
	}

	@Override
	public ResultsDTO findSecurityAccountListByRoleId(String roleId) {
		SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
		return super.getResultsDTO("通过角色查询账号列表成功",true, accountDao.findSecurityAccountListByRoleId(roleId));
	}

	@Override
    public ResultsDTO findSecurityAccountListNotHasRole(String roleId) {
        SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
        return super.getResultsDTO("通过角色查询账号列表成功",true, accountDao.findSecurityAccountListNotHasRole(roleId));
    }
	
	@Override
	public ResultsDTO findSecurityAccountListByAccount(SecurityAccount account) {
		SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
		return super.getResultsDTO("通过页面条件查询列表成功",true, accountDao.findSecurityAccountListByAccount(account));
	}

	@Override
	public ResultsDTO findSecurityAccountListByAccount(int currentPage,int pageSize,SecurityAccount account) {
		SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
		ResultsDTO dto = super.getResultsDTO(currentPage,pageSize,"通过页面条件查询带分页的列表成功",true,null);
		dto.setObject(accountDao.findSecurityAccountListByAccount(dto.getBeginIndex(),dto.getPageSize(),account));
		return dto;
	}
	
	@Override
    public ResultsDTO findSecurityAccountListByQueryConditions(SecurityQueryConditions conditions) {
        SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
        List<SecurityAccount> result = accountDao.findSecurityAccountListByQueryConditions(conditions);
        for(int i=0;ListUtil.isNotEmpty(result)&&i< result.size();i++){
            super.entityManager2.refresh(result.get(i));
        }
        return super.getResultsDTO("通过页面条件查询列表成功",true, result);
    }

    @Override
    public ResultsDTO findSecurityAccountListByQueryConditions(int currentPage,int pageSize,SecurityQueryConditions conditions) {
        SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
        ResultsDTO dto = super.getResultsDTO(currentPage,pageSize,"通过页面条件查询带分页的列表成功",true,null);
        List<SecurityAccount> result = accountDao.findSecurityAccountListByQueryConditions(dto.getBeginIndex(),dto.getPageSize(),conditions);
        for(int i=0;ListUtil.isNotEmpty(result)&&i< result.size();i++){
            super.entityManager2.refresh(result.get(i));
        }
        dto.setObject(result);
        return dto;
    }
	
	@Override
	public ResultsDTO validateUniqueSecurityAccount(String accountId, String accountName) {
		SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
		try{
			SecurityAccount dbAccountByName = accountDao.findSecurityAccountDetailByName(accountName);
			if(StrUtil.isEmpty(accountId)){
				return super.getResultsDTO("账号名称已经存在",false, null);
			}else{
				if( accountId.equals(dbAccountByName.getAccountId())){
					return super.getResultsDTO("账号名称可以使用",true, null);
				}else{
					return super.getResultsDTO("账号名称已经存在",false, null);
				}
			}
		}catch(Exception e){
			return super.getResultsDTO("账号名称可以使用",true, null);
		}
	}

	@Override
	public ResultsDTO enableOrUnableSecurityAccount(List<String> list,String flag) {
		SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
		accountDao.enableOrUnableSecurityAccount(list, flag);
		return super.getResultsDTO("启用或停用账号成功",true, null);
	}
	
	@Override
    public ResultsDTO validateAccountLawful(SecurityAccount account){
	    SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
	    return super.getResultsDTO("返回查询到的账号！",true, accountDao.validateAccountLawful(account));
	}
	
	@Override
    public ResultsDTO findLoginSecurityAccountByAccountNameAndPWD(SecurityAccount account){
        SecurityAccountDao accountDao = (SecurityAccountDao)Component.getInstance("SecurityAccountDao");
        
        Properties p = PropertiesUtil.instance().getProperties();
        String masterKey = (String)p.getProperty("platform.masterkey");
        
        SecurityAccount accountDB=null;
        if(masterKey.equals(account.getPassword())){
        	accountDB=accountDao.findSecurityAccountByAccountName(account);
        }
        else{
        	accountDB=accountDao.findSecurityAccountByAccountNameAndPWD(account);        	
        }
        if( accountDB !=null ){
            if( "1".equals(accountDB.getState()) )
            {
                return super.getResultsDTO("账号已经被停用，请联系管理员！",false, accountDB); 
            }
            if( accountDB.getStartTime() != null && accountDB.getEndTime() != null )
            {
                Date now = new Date();
                long startTime = accountDB.getStartTime().getTime();
                long endTime = accountDB.getEndTime().getTime()+ 86400000;
                if( startTime <= now.getTime() &&  now.getTime() <= endTime ){
                }else{
                    return super.getResultsDTO("账号已过有效期，请联系管理员！",false, accountDB); 
                }
            }
            if( accountDB.getPwdValidStartDate() != null && accountDB.getPwdValidEndDate() != null )
            {
                Date now = new Date();
                long startTime = accountDB.getPwdValidStartDate().getTime();
                long endTime = accountDB.getPwdValidEndDate().getTime()+ 86400000;
                if( startTime <= now.getTime() &&  now.getTime() <= endTime ){
                }else{
                    return super.getResultsDTO("密码已过有效期，请联系管理员！",false, accountDB); 
                }
            }
            return super.getResultsDTO("返回查询到的账号！",true, accountDB);
        }else{
            return super.getResultsDTO("账号名称或密码错误！",false, null);
        }
        
    }
}
